<?php
/**
 * Created by PhpStorm.
 * User: mr.lee
 * Date: 2018/6/4
 * Time: 上午8:49
 */

namespace app\common\controller;


use app\api\controller\Pay;
use app\api\controller\Pub;
use app\common\model\CardCzgive;
use app\common\model\CardCzLog;
use app\common\model\CardUserGet;
use app\common\model\CardUserLog;
use app\common\model\CardUserUpdate;
use app\common\model\Paylog;
use Wechat\Wxobjopen;

class Balance extends Wxoption
{
    public function checkbalance($arr, $user, $card)
    {
        $Pub=new Pub();
        $yf_price = $arr['add_balance'];
        if ($user['cs_balance'] <> 0) {
            //判断赠送金额是否超过核销金额
            $CardUserGet = new CardUserGet();
            if ($user['cs_balance'] < $arr['add_balance']) {
                //赠送金额归0
                $CardUserGet->where(['id' => $user['id']])->setField('cs_balance', 0);
                $dedures['del_balance'] = bcsub($arr['add_balance'] ,$user['cs_balance'],2);                             //实际支付额
            } else {
                $CardUserGet->where(['id' => $user['id']])->setDec('cs_balance', $arr['add_balance']);
                $arr['cs_balance'] = isset($arr['cs_balance'])?$arr['cs_balance']:$user['cs_balance'];
                $dedures['del_balance'] = bcsub($arr['add_balance'] , $arr['cs_balance'],2);
            }
            $dedures['del_balance'] = 0;
            $dedures['dis_card_zk'] = 0;                                          //会员折扣
            $dedures['vip_card_zk'] = 0;                                                //等级折扣
            $dedures['gel_card_zk'] = 0;                                                //卡券折扣
            $dedures['mach_zk'] = 0;                                                //门店折扣
            $dedures['hx_card'] = 0;                                                          //要核销的卡券
        } else {
            $params['merchantid'] = $arr['mid'];
            $params['total_fee'] = $arr['add_balance'];
            $params['orderid'] = $arr['orderid'];
            $MachExtend = new MachExtend();
            $machzk = $MachExtend->get_machzk($params);
            //已有门店折扣的情况下不再查询会员折扣
            if ($machzk['is_machzk'] == 'Y') {
                $dedures = $machzk;
            } else {
                $CardDedu = new CardDedu();
                $dedures = $CardDedu->getzk($arr, $user, $card);
                $dedures['mach_zk'] = 0;
            }

        }
        $darr['dis_card_zk'] = $dedures['dis_card_zk'];                                                 //会员折扣
        $darr['vip_card_zk'] = $dedures['vip_card_zk'];                                                 //等级折扣
        $darr['gel_card_zk'] = $dedures['gel_card_zk'];                                                 //卡券折扣
        $darr['mach_zk'] = $dedures['mach_zk'];                                                         //门店折扣
        $total_fee= $dedures['dis_card_zk']+$dedures['vip_card_zk']+$dedures['gel_card_zk']+$dedures['mach_zk'];            //折扣总金额
        $darr['hx_card'] = $dedures['hx_card'];                                                         //要核销的卡券
        $darr['yf_balance'] = $yf_price;                                                                //应付金额
        $darr['del_balance'] = bcsub($yf_price,$total_fee,2);                                     //实际支付额
        $darr['add_balance'] = '';
        $darr['pay_balance'] = $arr['add_balance'];                                                     //实际支付额
        return $darr;
    }

    public function paylog_rec($arr)
    {
        //订单记录
        $arr['mach_zk'] = isset($arr['mach_zk'])?$arr['mach_zk']:0;
        $datalog['mid'] = $arr['mid'];                          //mid
        $datalog['orderid'] = $arr['orderid'];     //订单号
        $datalog['pay_statu'] = 1;                              //交易状态
        $datalog['price'] = $arr['pay_balance'];               //支付金额
        $datalog['pay_time'] = date('Y-m-d H:i:s');     //支付时间
        $datalog['add_time'] = time();                              //支付时间戳
        $datalog['pay_fs'] = $arr['pay_fs'];                                     //支付方式
        //折、抵扣      未加入
        $datalog['openid'] = $arr['openid'];                //会员openid
        //核销时使用
        if ($arr['type'] == 2) {
            $datalog['yf_price'] = $arr['yf_price'];        //应付金额
            $Pub=new Pub();

            $datalog['gel_card_zk'] = $arr['gel_card_zk'];          //抵扣金额
            $datalog['vip_card_zk'] = $arr['vip_card_zk'];          //等级折扣金额
            $datalog['dis_card_zk'] = $arr['dis_card_zk'];          //会员折扣金额
            $datalog['mach_zk'] = $arr['mach_zk'];                  //门店折扣金额
            $datalog['hx_card'] = $arr['hx_card'];                   //抵扣卡券
            $datalog['zk_price'] = $Pub->format_price($arr['gel_card_zk']+ $arr['vip_card_zk']+$arr['dis_card_zk']+$arr['mach_zk']);     //折扣金额
        } elseif ($arr['type'] == 1) {
            $datalog['pay_cate'] = "recharge";
            $datalog['yf_price'] = $arr['pay_balance'];
        }
        if (isset($arr['card_num'])){
            $datalog['card_num'] = $arr['card_num'];
        }
        //END
        $datalog['d_cashier'] = $arr['nickname'];               //操作人
        $maps['mid'] = $arr['mid'];
        $maps['orderid'] = $arr['orderid'];
        $Paylog = new Paylog();
        $payloginfo = $Paylog->where($maps)->find();
        if ($payloginfo) {
            $Paylog->allowField(true)->save($datalog, ['orderid' => $arr['orderid']]);
        } else {
            $Paylog->allowField(true)->save($datalog);
        }


        $res = $datalog;
        //核销卡券
        $CardDedu = new CardDedu();
        $resc = $CardDedu->pay_hx_card($datalog);
        return $res;
    }

    //更新记录 CardUserUpdate
    public function cardupdate($arr, $user, $arrc)
    {
        $datas['code'] = $user['code'];
        $datas['card_id'] = $user['card_id'];
        $datas['openid'] = $user['openid'];
        if (isset($arr['record'])) {
            $datas['record_balance'] = $arr['record'];
        }
        $datas['pay_balance'] = $arrc['pay_balance'];
        $datas['add_balance'] = $arrc['add_balance'];
        $datas['mid'] = $arr['mid'];
        if (isset($arr['giveid'])) {
            $datas['giveid'] = $arr['giveid'];
        }
        if (isset($arr['del_balance'])) {
            $datas['del_balance'] = $arrc['del_balance'];
        }
        if (isset($arr['add_bonus'])) {
            $datas['add_bonus'] = $arr['add_bonus'];
        }
        $datas['con_username'] = $arr['nickname'];
        $datas['hx_fs'] = $arr['hx_fs'];
        $datas['type'] = $arr['type'];
        $datas['cate'] = $arr['cate'];
        $datas['reason'] = $arr['reason'];
        $datas['source'] = $arr['source'];
        $datas['create_time'] = time();
        $datas['orderid'] = isset($arr['orderid']) ? $arr['orderid'] : "";
        $CardUserUpdate = new CardUserUpdate();
        $resut = $CardUserUpdate->allowField(true)->save($datas);
        if ($resut) {
            //carduserlog记录
            $updataid = $CardUserUpdate->id;
            $datas['up_id'] = $updataid;
            $datas['orderid'] = $arr['orderid'];
            $this->rec_cardlog($datas);
            //有赠送金额时再次新增记录
            if ($arrc['pay_balance'] < $arrc['add_balance']) {
                $datas['num'] = $arrc['add_balance'] - $arrc['pay_balance'];
                $datas['cate'] = 2;         //余额
                $datas['reason'] = 2;         //原因
                unset($datas['add_bonus']);
                $r = $this->rec_cardlog($datas);
            }
        } else {
            $updataid = '';
        }
        return $updataid;
    }

    //记录表
    public function rec_cardlog($arr)
    {
        try {
            $CardUserLog = new CardUserLog();
            $data['mid'] = $arr['mid'];
            $data['up_id'] = $arr['up_id'];
            $data['openid'] = $arr['openid'];
            $data['orderid'] = $arr['orderid'];
            $data['con_username'] = $arr['con_username'];
            $data['card_id'] = $arr['card_id'];
            $data['code'] = $arr['code'];
            //是否余额赠送
            if (!isset($arr['num'])) {
                if (isset($arr['pay_balance'])) {
                    if ($arr['type'] == 2) {
                        $data['num'] = -$arr['pay_balance'];
                    } else {
                        $data['num'] = $arr['pay_balance'];
                    }
                }
                if (isset($arr['del_balance'])) {
                    $data['num'] = -$arr['del_balance'];
                }
            } else {
                //赠送余额
                $data['num'] = $arr['num'];
            }
            if (isset($arr['record_balance'])) {
                $data['record'] = $arr['record_balance'];           //记录
            }
            $data['type'] = $arr['type'];               //1充值/2核销
            $data['cate'] = $arr['cate'];               //1积分/2余额
            $data['reason'] = $arr['reason'];           //原因
            $data['source'] = $arr['source'];           //来源
            $data['create_time'] = time();
            $res = $CardUserLog->allowField(true)->save($data);
            $ComBonus = new Bonus();
            if (isset($arr['add_bonus'])) {
                $data['add_bonus'] = $arr['add_bonus'];
                $data['cate'] = 1;               //1积分/2余额
                $data['reason'] = 2;           //原因
                $ComBonus->rec_cardlogs($data);
            }

        } catch (\Exception $e) {
            $res = ['errcode' => 9911, 'message' => $e->getMessage()];
        }
        return $res;
    }

    //余额更新微信操作  系统通知
    public function updatebalance($arr)
    {
        //实例化微信
        $options = $this->options($arr['card_id'], 'card_id');
        $WxObj = new Wxobjopen($options);
        $data = [
            'code' => $arr['code'],
            'card_id' => $arr['card_id'],
            'custom_field_value2' => $arr['price'] . '元',
            'notify_optional' => [
                'is_notify_bonus' => false,
                'is_notify_balance' => false,
                'is_notify_custom_field2' => false,
            ],
        ];
        $res = $WxObj->updateUserInfo($data);
        return $res;
    }

    public function cardczlog_rec($datalog, $user, $datas, $arr)
    {
        $czdata['orderid'] = $datalog['orderid'];
        $czdata['openid'] = $user['openid'];
        $czdata['cz_price'] = $datas['pay_balance'];
        $czdata['zs_price'] = $datas['add_balance'] - $datas['pay_balance'];
        $czdata['giveid'] = $arr['giveid'];
        $czdata['statu'] = 1;
        $czdata['code'] = $user['code'];
        $czdata['addtime'] = $datalog['add_time'];
        $CardCzLog = new CardCzLog();
        $resut = $CardCzLog->allowField(true)->save($czdata);
        if ($resut) {
            $give_rec_id = $CardCzLog->id;
            return $give_rec_id;
        }
    }

    //冲送判断
    public function cs_type($arr, $user)
    {
        if (!empty($arr['giveid'])) {
            $CardZsgive = new CardCzgive();
            $givetype = $CardZsgive->where(['id' => $arr['giveid']])->value('type');
            $ComCardPut = new CardPut();
            if ($givetype == 1) {
                $arrd['mid'] = $arr['mid'];
                $arrd['top_mid'] = $arr['top_mid'];
                $arrd['giveid'] = $arr['giveid'];
                $arrd['give_rec_id'] = $arr['give_rec_id'];
                $arrd['card_id'] = $user['card_id'];
                $arrd['openid'] = $user['openid'];
                $arrd['nickname'] = $user['nickname'];
                $arrd['code'] = $user['code'];
                $arrd['get_card_id'] = $user['id'];
                $resut = $ComCardPut->regSgive($arrd);        //新规则，赠送多张
//                $uend['zs_card'] = json_encode($resut['card'], JSON_UNESCAPED_UNICODE);
//                $uend['zs_bonus'] = json_encode($resut['bonus'], JSON_UNESCAPED_UNICODE);
//                $CardUserUpdate = new CardUserUpdate();
//                $res = $CardUserUpdate->where(['id' => $arr['updataid']])->update($uend);
                $res = 1;
            } else {
                //赠送方法
                $sparams['give_rec_id'] = $arr['give_rec_id'];
                $sparams['get_card_id'] = $user['id'];
                $sparams['card_id'] = $user['card_id'];
                $sparams['giveid'] = $arr['giveid'];
                $sparams['openid'] = $user['openid'];
                $sparams['nickname'] = $user['nickname'];
                $sparams['code'] = $user['code'];
                $resut = $ComCardPut->czgive($sparams);       //原规则
//                $uend['zs_card'] = json_encode($resut['card'], JSON_UNESCAPED_UNICODE);
//                $uend['zs_bonus'] = json_encode($resut['bonus'], JSON_UNESCAPED_UNICODE);
//                $CardUserUpdate = new CardUserUpdate();
//                $res = $CardUserUpdate->where(['id' => $arr['updataid']])->update($uend);
                $res = 1;
            }

        } else {
            $res = 1;
        }
        return $res;
    }
}